<?php
/**
 * common.func.php
 * User: yzm
 * Date: 2017/7/25
 */

/*
 * 日期格式化 时间戳转为类型日期
 * @params int $timestamp
 * @params string $format
 * return string
 */
function format($timestamp, $format = 'Y-m-d H:i:s') {
    return date($format, $timestamp);
}

/*
 * 去掉数组中的字段key值
 * @params array $data
 * @params string $field
 * return array
 */
function return_array_value($data, $field) {
    $res = array();
    if (empty($data) || empty($field)) {
        return array();
    }
    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $res[] = $value[$field];
        }
        return $res;
    } else {
        return array();
    }
}

/*
 * 去除标点符号
 * @param string keyword 过滤的字符串
 * return string
 */
function filter_punctuation($keyword = '') {
    if (empty($keyword)) {
        return '';
    }
    $keyword=urlencode($keyword);//将关键字编码
    $keyword=preg_replace("/(%7E|%60|%21|%40|%23|%24|%25|%5E|%26|%27|%2A|%28|%29|%2B|%7C|%5C|%3D|\-|_|%5B|%5D|%7D|%7B|%3B|%22|%3A|%3F|%3E|%3C|%2C|\.|%2F|%A3%BF|%A1%B7|%A1%B6|%A1%A2|%A1%A3|%A3%AC|%7D|%A1%B0|%A3%BA|%A3%BB|%A1%AE|%A1%AF|%A1%B1|%A3%FC|%A3%BD|%A1%AA|%A3%A9|%A3%A8|%A1%AD|%A3%A4|%A1%A4|%A3%A1|%E3%80%82|%EF%BC%81|%EF%BC%8C|%EF%BC%9B|%EF%BC%9F|%EF%BC%9A|%E3%80%81|%E2%80%A6%E2%80%A6|%E2%80%9D|%E2%80%9C|%E2%80%98|%E2%80%99)+/",'',$keyword);
    $keyword=urldecode($keyword);//将过滤后的关键字解码
    return $keyword;
}

/*
 * 计算中文字符串长度
 * @param string $string 字符串
 * return num
 */
function utf8_strlen($string = '') {
    // 将字符串分解为单元
    preg_match_all("/./us", $string, $match);
    // 返回单元个数
    return count($match[0]);
}

/*
 * 截取UTF-8编码下字符串的函数
 * @param $sourcestr string 需要截取的字符串
 * @param $cutlength int 截取长度
 * @param $ellipsis 截取后带的符号
 * @return  string
 */
function cut_substr($sourcestr,$cutlength,$symbol='') {
    $returnstr='';
    $i=0;
    $n=0;
    $str_length=strlen($sourcestr);//字符串的字节数
    while (($n<$cutlength) and ($i<=$str_length)) {
        $temp_str=substr($sourcestr,$i,1);
        $ascnum=ord($temp_str);//得到字符串中第$i位字符的ascii码
        if ($ascnum>=224)    //如果ASCII位高与224，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i=$i+3;            //实际Byte计为3
            $n++;            //字串长度计1
        }
        elseif ($ascnum>=192) //如果ASCII位高与192，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i=$i+2;            //实际Byte计为2
            $n++;            //字串长度计1
        }
        elseif ($ascnum>=65 && $ascnum<=90) //如果是大写字母，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1;            //实际的Byte数仍计1个
            $n++;            //但考虑整体美观，大写字母计成一个高位字符
        }
        else                //其他情况下，包括小写字母和半角标点符号，
        {
            $returnstr=$returnstr.substr($sourcestr,$i,1);
            $i=$i+1;            //实际的Byte数计1个
            $n=$n+0.5;        //小写字母和半角标点等与半个高位字符宽...
        }
    }
    if ($str_length>$cutlength){
        $returnstr = $returnstr . $symbol;//超过长度时在尾处加上省略号
    }
    return $returnstr;
}

/*
 * 获取系统高配置信息
 * @param string $name
 * return array/string
 */
function getSite($name = '', $w = ''){
    global $_W;
    $uniacid = empty($w) ? $_W['uniacid'] : $w;
    if (empty($uniacid)) {
        $setting = pdo_get('wherein_knowledge_setting');
    } else {
        $setting = pdo_get('wherein_knowledge_setting', array('uniacid' => $uniacid));
    }
    $setting = unserialize($setting['value']);

    if (empty($name)) {
        return $setting;
    } else {
        return $setting[$name];
    }
}

/*
 * 生成订单唯一编号
 * return string
 */
function create_order_sn() {
    $order_sn = '';
    $order_sn = date('YmdHi') . mt_rand(1000, 9999);
    return $order_sn;
}

/*
 * 模板 - 填写工单
 * @param string $openid 用户openid
 * @param string $cat_name 分类名
 * @param string $content 内容
 * @param string $url 跳转链接
 */
function workorder_msg($openid, $cat_name, $content = '', $url='') {
    $send_id = getSite('workorder_msg');

    $content = empty($content) ? '工单已经提交成功, 感谢您的宝贵意见,客服会尽快给您回复,请你耐心等待~' : $content;

    $postdata = array(
        "first" => array(
            "value" => "尊敬的客户您好,您有新的工单提醒",
            "color" => "#4a5077"
        ),
        "keyword1" => array(
            'value' => $cat_name,
            "color" => "#4a5077"
        ),
        "keyword2" => array(
            'value' => $content,
            "color" => "#4a5077"
        ),
        "remark" => array(
            "value" => '点击查看!',
            "color" => "#4a5077"
        ),
    );
    $account_api = WeAccount::create();
    $account_api->sendTplNotice($openid, $send_id, $postdata, $url);
}

/*
 * 模板 - 收到回复
 * @param string $openid 用户openid
 * @param string $cat_name 分类名
 * @param string $content 内容
 * @param string $date 日期
 * @param string $url 跳转链接
 */
function receive_msg($openid, $cat_name, $content = '', $date, $url='') {
    $send_id = getSite('receive_msg');

    $content = empty($content) ? '您于' . $date . '提交的关于“' . $cat_name . '”的工单收到回复了，赶紧无看看吧~感谢您的耐心等待与支持' : $content;

    $postdata = array(
        "first" => array(
            "value" => "尊敬的客户您好,您有新的工单提醒",
            "color" => "#4a5077"
        ),
        "keyword1" => array(
            'value' => $cat_name,
            "color" => "#4a5077"
        ),
        "keyword2" => array(
            'value' => $content,
            "color" => "#4a5077"
        ),
        "remark" => array(
            "value" => '点击查看!',
            "color" => "#4a5077"
        ),
    );
    $account_api = WeAccount::create();
    $account_api->sendTplNotice($openid, $send_id, $postdata, $url);
}

function getInfo() {
    global $_W, $_GPC;
    $userinfo = array();
    load()->model('mc');
    $userinfo = mc_oauth_userinfo();
    if (empty($userinfo['openid'])) {
        die("<!DOCTYPE html>
            <html>
                <head>
                    <meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'>
                    <title>抱歉，出错了</title><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, user-scalable=0'><link rel='stylesheet' type='text/css' href='https://res.wx.qq.com/connect/zh_CN/htmledition/style/wap_err1a9853.css'>
                </head>
                <body>
                <div class='page_msg'><div class='inner'><span class='msg_icon_wrp'><i class='icon80_smile'></i></span><div class='msg_content'><h4>请在微信客户端打开链接</h4></div></div></div>
                </body>
            </html>");
    }
    return $userinfo;
}

/*
 * 解析获取php.ini 的upload_max_filesize（单位：byte）
 * @return float （单位：byte）
 */
function get_upload_max_filesize_byte(){
    $max_size = ini_get('upload_max_filesize');
    preg_match('/(^[0-9\.]+)(\w+)/',$max_size, $info);
    $size = $info[1];
    $suffix = strtoupper($info[2]);

    if ($suffix == 'B') {
        $filesize = $size;
    } else if ($suffix == 'K' || $suffix == 'KB') {
        $filesize = round($size * 1024);
    } else if ($suffix == 'M' || $suffix == 'MB') {
        $filesize = round($size * 1024 * 1024);
    } else if ($suffix == 'G' || $suffix == 'GB') {
        $filesize = round($size * 1024 * 1024 * 1024);
    } else {
        $filesize = 1024*1024*2;
    }
    return $filesize;
}

/*
 * 导出csv
 */
function work_order_export_parse($order_list){
    if (empty($order_list)) {
        return false;
    }
    $header = array(
        'order_sn' => '工单号', 'nickname' => '客户信息', 'reply_num' => '回复次数',
        'add_time' => '创建时间','update_time' => '最近回复时间', 'order_status_name' => '工单状态',
        'customer_status_name' => '客户状态', 'content' => '工单详情', 'pic' => '附件名称'
    );
    $keys = array_keys($header);
    $html = "\xEF\xBB\xBF";
    foreach ($header as $li) {
        $html .= $li . "\t ,";
    }
    $html .= "\n";
    $count = count($order_list);
    $pagesize = ceil($count/5000);
    for ($j = 1; $j <= $pagesize; $j++) {
        $list = array_slice($order_list, ($j-1) * 5000, 5000);
        if (!empty($list)) {
            $size = ceil(count($list) / 500);
            for ($i = 0; $i < $size; $i++) {
                $buffer = array_slice($list, $i * 500, 500);
                $order = array();
                foreach ($buffer as $row) {
                    $data = array();
                    foreach ($keys as $key) {
                        $data[] = $row[$key];
                    }
                    $order[] = implode("\t ,", $data) . "\t ,";
                    unset($data);
                }
                $html .= implode("\n", $order) . "\n";
            }
        }
    }
    return $html;
}

/*
 * 判断是安卓还是ios
 */
function get_device_type() {
    //全部变成小写字母
    $agent = strtolower($_SERVER['HTTP_USER_AGENT']);
    $type = 'other';
    //分别进行判断
    if(strpos($agent, 'iphone') || strpos($agent, 'ipad')) {
        $type = 'ios';
    }

    if(strpos($agent, 'android')) {
        $type = 'android';
    }
    return $type;
}

/*
 * 调试方法
 */
function p() {
    $getArgs = func_get_args();
    if (in_array(end($getArgs), array('y', 'n'))) {
        $is_exit = end($getArgs);
        array_pop($getArgs);
    } else {
        $is_exit = 'y';
    }
    foreach ($getArgs as $key => $value) {
        echo '<pre>';
        var_dump($value);
    }
    if ($is_exit == 'y') {
        exit;
    }
}